const regeneratorRuntime = require('../../vendor/regenerator-runtime')
const co = require('../../vendor/co')
const numeral = require("../../vendor/numeral/numeral.min")
const app = getApp()
let userInfo = { name: "", phone: "" }
const amapFile = require("../../vendor/amap-wx")

Page({
    data: {
        num: 1, isStore: false, currentStore: -1,
        couponsList: false
    },
    onLoad: function (options) {
        this.setData(options)
    },
    //获取商品信息和收货地址
    onShow() {
        this.loadData()
    },

    loadData() {
        wx.showLoading({
            title: '加载中...',
        })
        const data = { id: this.data.id }
        this.data.tid && (data.tid = this.data.tid)
        this.data.tid2 && (data.tid2 = this.data.tid2)
        this.data.sku_id && (data.sku_id = this.data.sku_id)

        app.http.get("goods/pay-info", {
            data,
        }).then(res => {
            if (this.data.store) {
                delete res.data.store
            }

            this.setData(
                Object.assign({ loading: false }, res.data),
            )
            this.setData({
                coupons: this.data.coupon_info
            })
            if (this.data.sku) {
                const skus = this.data.sku.name.split("#")
                for (let i = 0; i < this.data.goods_spec.length; i++) {
                    this.setData({
                        [`goods_spec[${i}].selected`]: this.data.goods_spec[i].child.findIndex(o => o.name == skus[i])
                    })
                }
            }
            this.originSpec = this.data.goods_spec.map(o => Object.assign({}, o))

            if (!this.gdmap) {
                this.gdmap = new amapFile.AMapWX({ key: res.data.gaode_key });
            }
            this.up = false
            this.getPrice()
            this.getTotalPrice()
            wx.hideLoading()
        })
        wx.getStorage({
            key: 'address',
            success: res => {
                this.setData({
                    address: res.data
                })
            },
        })
    },

    bindSale() {
        this.setData({
            couponsList: true
        })
    },
    radioChange(e) {
        var coupons_checked = this.data.coupons.filter(o => e.detail.value == o.id)
        this.setData({
            coupons_checked: coupons_checked,
            coupons_name: coupons_checked[0].name,
            coupons_id: parseInt(e.detail.value),
        })
    },
    couponsCancel() {
        this.setData({
            couponsList: false,
        })
        this.getTotalPrice()

    },


    //获取商品单价
    getPrice() {
        if (!this.up) {
            let p = this.data.mall_price
            if (this.data.goodsTeams) {
                p = this.data.goodsTeams.price
            }
            p = +p
            if (this.data.sku) {
                p += (this.data.sku.price / 100)
            }
            p = Math.max(0.01, p)
            const ps = getCurrentPages()
            // if (ps[ps.length - 2].route == "pages/goods/lucky") {
            if (this.data.lucky) {
                p = 0.01
                this.setData({
                    disableNum: true
                })
            }
            this.setData({
                price: numeral(p).format("0,0.00")
            })
            this.up = p

        }
        return this.up
    },

    showSku() {
        this.setData({
            isDetailShow: true,
            goods_spec: this.originSpec
        })
    },
    hideSku() {
        this.setData({
            isDetailShow: false,
        })
    },
    clickSpec(evt) {
        const { row, col } = evt.currentTarget.dataset
        this.setData({
            [`goods_spec[${row}].selected`]: col
        })
        let skuName = this.data.goods_spec.map(o => {
            return o.child[o.selected] ? o.child[o.selected].name : "--"
        }).join("#")
        const selectedSku = this.data.goods_sku.find(o => o.name == skuName)
        this.setData({
            selectedSku,
        })
    },
    submitSku() {
        if (!this.data.selectedSku) {
            app.wxToast.warn("请选择" + this.data.goods_spec.filter(o => o.selected == undefined || o.selected < 0)[0].name)
            return
        }
        this.setData({
            isDetailShow: false,
            sku_id: this.data.selectedSku.id,
        })
        this.loadData()
    },

    //获取总价
    getTotalPrice() {
        let total = this.getPrice() * this.data.num
        if (this.data.coupons_checked) {
            if (this.data.totalPrice >= this.data.coupons_checked[0].use_condition){
                if (this.data.coupons_checked[0].type == 1) {
                    total = total - (this.data.coupons_checked[0].price - 0)
                }
                if (this.data.coupons_checked[0].type == 2) {
                    total = total * (this.data.coupons_checked[0].discount / 10)
                }
            }
        }
        this.setData({
            totalPrice: numeral(total).format("0,0.00")
        })
    },

    num_plus: function () {
        let num = this.data.num + 1
        this.updateNum(num)
    },

    num_minus: function () {
        let num = this.data.num - 1
        this.updateNum(num)
    },

    numInput: function (evt) {
        let num = evt.detail.value
        this.updateNum(num)
        return this.data.num
    },

    updateNum: function (num) {
        if (num < 1) num = 1
        if (num > this.data.max_amount) {
            num = this.data.max_amount
        }
        this.setData({
            num
        })
        this.getTotalPrice()
    },

    onInput: function (evt) {
        userInfo[evt.currentTarget.dataset.key] = evt.detail.value
    },


    pay() {
        if (this.data.isSelf) {
            if (this.data.currentStore < 0) {
                app.wxToast.warn("请选择收货门店")
                return
            }
            if (!userInfo.name) {
                app.wxToast.warn("请输入姓名")
                return
            }
            if (!userInfo.phone) {
                app.wxToast.warn("请输入电话")
                return
            }
        } else {
            if (!this.data.address) {
                app.wxToast.warn("请选择收货地址")
                return
            }
        }

        if (this.data.goods_spec && this.data.goods_spec.length && !this.data.sku && !this.data.lucky) {
            this.showSku()
            return
        }

        if (this.data.paying) {
            return
        }
        this.setData({
            paying: true
        })
        let data = {
            goods_id: this.data.id,
            quantity: this.data.num,
            coupon_id: this.data.coupons_id || 0
        }
        let url = 'order/create'
        if (this.data.tid) {
            //开团
            url = "group-order/create"
            data.goods_team_id = this.data.tid
        }
        if (this.data.tid2) {
            //参团
            url = "group-order/join"
            data.order_id = this.data.tid2
        }
        if (this.data.sku_id) {
            //商品规格
            data.sku_id = this.data.sku_id
        }

        if (this.data.isSelf) {
            data['sub_store_id'] = this.data.store[this.data.currentStore].id
            data['phone'] = userInfo.phone
            data['consignee'] = userInfo.name
        } else {
            data = Object.assign(data, this.data.address)
        }
        data.remark = this.remark || ""
        app.http.post(url, {
            data,
        }).then(result => {
            let jspay = result.data.js
            let orderId = result.data.items.id
            this.setData({ paying: false })
            if (this.data.tid && this.data.goodsTeams.is_free) {
                wx.redirectTo({
                    url: '../pt/ok/ok?id=' + orderId
                })
                return
            }

            const obj = Object.assign(jspay, {
                success: res => {
                    if (this.data.join) {
                        wx.navigateBack({

                        })
                    } else {
                        let p = '../personal/order/detail?id=' + orderId
                        if (this.data.tid) {
                            p = '../pt/ok/ok?id=' + orderId
                        }
                        if (this.data.tid2 && !this.data.lucky) {
                            p = '../pt/ok/ok?id=' + this.data.tid2
                        }
                        wx.redirectTo({
                            url: p
                        })
                    }

                },
                fail: err => {
                    app.wxToast.warn("支付失败，请重新支付")
                }
            })
            wx.requestPayment(obj)
        }).catch(err => {
            console.log(err)
            app.wxToast.error(err.message)
            this.setData({ paying: false })
        })
    },

    //选择收货地址
    selectAddress() {
        app.toPromise(wx.chooseAddress).then(res => {
            const address = {
                consignee: res.userName,
                phone: res.telNumber,
                province: res.provinceName,
                city: res.cityName,
                country: res.countyName,
                address_detail: res.detailInfo
            }
            this.setData({
                address
            })

            wx.setStorage({
                key: 'address',
                data: address,
            })
        }).catch(err => {

        })
    },

    //选择门店
    selectStore() {
        this.setData({
            isMoreStore: !this.data.isMoreStore
        })
    },
    submitStore(evt) {
        this.setData({
            currentStore: evt.currentTarget.dataset.index,
        })
    },
    stop() { },

    //到店自取
    onSelf(evt) {
        const val = evt.detail.value
        this.setData({
            isSelf: val
        })


        if (val) {
            co(function* () {
                try {
                    const location = yield app.toPromise(wx.getLocation)
                    const results = yield Promise.all(this.data.store.map(o => {
                        return new Promise((resolve, reject) => {
                            this.gdmap.getDrivingRoute({
                                origin: location.longitude + "," + location.latitude,
                                destination: o.lng + "," + o.lat,
                                success: res => {
                                    resolve(Object.assign(o, { distance: parseFloat(res.paths[0].distance) }))
                                },
                                fail: err => {
                                    reject(err)
                                }
                            })
                        })
                    }))

                    for (let i = 0; i < results.length; i++) {
                        for (let j = 0; j < results.length; j++) {
                            if (results[i].distance <= results[j].distance) {
                                results.splice(j, 0, results[i]);
                                results.splice(i + 1, 1);
                                break;
                            }
                        }
                    }
                    this.setData({
                        store: results.map(o => {
                            if (o.distance < 1000) {
                                o.distancestr = o.distance + " m"
                            } else {
                                o.distancestr = (o.distance / 1000).toFixed(2) + " km"
                            }
                            return o
                        }),
                    })
                } catch (err) {
                    console.log(err)
                }

            }.bind(this))
        }
    },

    //在地图上查看门店
    openMap(evt) {
        wx.openLocation({
            latitude: '',
            longitude: '',
        })
    },

    makePhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.store[this.data.currentStore].phone,
        })
    },

    onRemark(evt) {
        this.remark = evt.detail.value
    },
})